/**
* Copyright © 2018-2019, by 晓叹星沉.
*/
package org.aurora.utils.bean;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

/**
 * 
 * <p>
 * bean处理工具类
 * </p>
 * @author 晓叹星沉
 * @since jdk1.8
 * 2019年4月18日
 *  
 */

public class BeanUtils extends org.apache.commons.beanutils.BeanUtils{

	private static final Map<String, String> DATE_FORMATS = new HashMap<String, String>(9);
	static{
		DATE_FORMATS.put("^[0-9]{4}[0-9]{2}[0-9]{2}[0-9]{2}[0-9]{2}[0-9]{2}$", "yyyyMMddHHmmss");
		DATE_FORMATS.put("^[0-9]{4}[0-9]{2}[0-9]{2}$", "yyyyMMdd");
		DATE_FORMATS.put("^[0-9]{4}\\-[0-9]{1,2}\\-[0-9]{1,2} [0-9]{1,2}\\:[0-9]{1,2}\\:[0-9]{1,2}$", "yyyy-MM-dd HH:mm:ss");
		DATE_FORMATS.put("^[0-9]{4}\\-[0-9]{1,2}\\-[0-9]{1,2} [0-9]{1,2}\\:[0-9]{1,2}\\:[0-9]{1,2}\\.[0-9]{1,3}$", "yyyy-MM-dd HH:mm:ss");
		DATE_FORMATS.put("^[0-9]{4}\\-[0-9]{1,2}\\-[0-9]{1,2}$", "yyyy-MM-dd");
		DATE_FORMATS.put("^[0-9]{4}\\-[0-9]{1,2}\\-[0-9]{1,2} [0-9]{1,2}\\:[0-9]{1,2}$", "yyyy-MM-dd HH:mm");
		DATE_FORMATS.put("^[0-9]{4}\\-[0-9]{1,2}\\-[0-9]{1,2} [0-9]{1,2}$", "yyyy-MM-dd HH");
		DATE_FORMATS.put("^[0-9]{4}\\/[0-9]{1,2}\\/[0-9]{1,2}$", "yyyy/MM/dd");
		DATE_FORMATS.put("^[0-9]{4}\\/[0-9]{1,2}\\/[0-9]{1,2} [0-9]{1,2}\\:[0-9]{1,2}\\:[0-9]{1,2}$", "yyyy/MM/dd HH:mm:ss");
		DATE_FORMATS.put("^[0-9]{4}\\/[0-9]{1,2}\\/[0-9]{1,2} [0-9]{1,2}\\:[0-9]{1,2}$", "yyyy/MM/dd HH:mm");
		DATE_FORMATS.put("^[0-9]{4}\\/[0-9]{1,2}\\/[0-9]{1,2} [0-9]{1,2}$", "yyyy/MM/dd HH");
		ConvertUtils.register(new Converter() {
            
            public Object convert(Class type, Object value) {
                try {
                	for (Entry<String, String> e : DATE_FORMATS.entrySet()) {
                		if (Pattern.matches(e.getKey(), value.toString())) {
                			//return new SimpleDateFormat(e.getValue().replaceAll("-", "").replaceAll("/", "").replaceAll(" ", "").replaceAll(":", "")).parse(value.toString());
                			return new SimpleDateFormat(e.getValue()).parse(value.toString());
                		}
                	}
				} catch (ParseException e) {
					throw new RuntimeException();
				}
                return null;
            }
        }, Date.class);
	}
	
	public static void setProperty(final Object bean, final String name, final Object value)
	        throws IllegalAccessException, InvocationTargetException {
        BeanUtilsBean.getInstance().setProperty(bean, name, value);
    }
	
}
